package com.xinzhi.savingpot.background.realm;



import com.xinzhi.savingpot.background.entity.User;
import com.xinzhi.savingpot.background.service.impl.UserServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

import org.springframework.beans.factory.annotation.Autowired;


public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserServiceImpl userService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了认证方法");

        UsernamePasswordToken userToken = (UsernamePasswordToken) token;

        User user = (User) userService.queryUserByName(userToken.getUsername());
        if (user == null) { //没有这个人
            return null;//抛出异常  UnknownAccountException
        }
        Subject currentSubject = SecurityUtils.getSubject();
        Session session = currentSubject.getSession();
        session.setAttribute("loginUser", user);
        /**
         * 密码认证，让shiro完成 加密了  使用MD5
         */
        return new SimpleAuthenticationInfo(user, user.getPassword(), "");
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("执行了授权方法");
        //根据身份信息 用户名 获取当前用户的角色信息，以及权限信息
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        info.addStringPermission("user:add");
//        info.addStringPermission("user:update");
        //拿到当前登录的这个对象
        Subject subject = SecurityUtils.getSubject();
        User principal = (User) subject.getPrincipal();
        //设置当前用户的权限
        info.addStringPermission(principal.getUserrole().getPerms());
        return info;
    }


}